package com.example.demo.controller;

import com.example.demo.entity.*;
import com.example.demo.mapper.CustomerMapper;
import com.example.demo.mapper.RunTableMapper;
import com.example.demo.service.*;
import com.example.demo.util.*;
import com.example.demo.util.wx.MD5Utils;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

//@Async
@RestController
@RequestMapping("customer")
public class CustomerController {


    @Autowired
    CustomerService customerService;
    @Autowired
    RunTableService runTableService;
    /**http://www.zhulipingtai.com/earn/customer/addCustomer?phone=18712882023&password=1234&inviter=56&verificationCode=123
     * 用户注册
     * @param customer
     * @return
     */
    @PostMapping("addCustomer")
    public JsonResult addCustomer(Customer customer){
        JsonResult json = new JsonResult();
        String str = customer.getPhone().substring(0,3);
        if(str.equals("170")||str.equals("171")){
            json.setSuccess(false);
            json.setMessage("170-171号段禁止注册");
        }else {
            json = customerService.addCustomer(customer);
        }
        return json;
    }
    /**localhost:6080/customer/login?phone=18712882023&password=1234
     * 用户登录
     * @param customer
     * @return
     */
    @PostMapping("login")
    public JsonResult login(Customer customer){
        JsonResult json = customerService.login(customer);
        Integer frozen = customerMapper.getFrozen(customer.getPhone());
        if(frozen!=null&&frozen==1){
            json.setMessage("您由于违规操作，账户已被冻结");
            json.setSuccess(false);
            return json;
        }
        return json;
    }
    /**localhost:6080/customer/upPassword?phone=18712882023&password=1234&newPassword=12
     * 修改密码
     * @param customer
     * @return
     */
    @PostMapping("upPassword")
    public JsonResult upPassword(Customer customer){
        JsonResult json = customerService.upPassword(customer);
        return json;
    }
    /**localhost:6080/customer/main?phone=12
     * 获取主页的所有数据
     * @param phone
     * @return
     */
    @GetMapping("main")
    public JsonResult main(String phone){
        JsonResult json = customerService.main(phone);
        return json;
    }
    /**localhost:6080/customer/personal?phone=12
     * 获取个人中心所有数据
     * @param phone
     * @return
     */
    @GetMapping("personal")
    public JsonResult personal(String phone){
        JsonResult json = customerService.personal(phone);
        return json;
    }
    /**localhost:6080/customer/material?materialType=1
     * 根据类型不同查询视频 1，推广 2，Q&A 3
     * @param materialType
     * @return
     */
    @GetMapping("material")
    public JsonResult material(String materialType){
        JsonResult json = customerService.material(materialType);
        return json;
    }
    /**localhost:6080/customer/withdrawals?phone=12
     * 提现记录
     * @param phone
     * @return
     */
    @GetMapping("withdrawals")
    public JsonResult withdrawals(String phone){
        JsonResult json = customerService.withdrawals(phone);
        return json;
    }


    @PostMapping("test")
    public JsonResult Test(){
        JsonResult json = new JsonResult();
        json.setMessage("dfghjkl;");
        return json;
    }

    /**
     * 是否绑定
     * @param phone
     * @return
     */
    @GetMapping("isBinding")
    public JsonResult isBinding(String phone){
        JsonResult json = customerService.isBinding(phone);
        return json;
    }
    /**localhost:6080/customer/payUrl
     * 获取绑定微信二维码
     * @return
     */
    @GetMapping("payUrl")
    public JsonResult payUrl(String phone){//http://www.p619.cn/
        JsonResult json = new JsonResult();
//        String urlWechat = "bang.z717.top";
        String urlWechat = customerMapper.selUrlWechat();
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc69b596fd4ff4c0c" +
                "&redirect_uri=http://"+urlWechat+"/earn/test.html&response_type=code&scope=snsapi_userinfo&state="+phone+"#wechat_redirect";
        json.setSuccess(true);
        json.setData(url);
        return json;
    }
    /**localhost:6080/customer/registerUrl
     * 获取分享页网址
     * @return
     */
    @GetMapping("registerUrl")
    public JsonResult registerUrl(String phone){
        JsonResult json = new JsonResult();
        String url = customerService.getUrl();
        //获取分享码
        String code = customerMapper.getInv(phone);
//        String url = ur+"zhuce/index.html?phone="+inv;
        Map map = new HashMap();
        map.put("url",url);
        map.put("code",code);
        json.setSuccess(true);
        json.setData(map);
        return json;
    }
    /**localhost:6080/customer/verificationCode?phone=18712882023
     * 注册,获取验证码
     * @return
     */
    @GetMapping(value = "/verificationCode")
    public JsonResult saveVerificationCode(String phone) {
        JsonResult json = new JsonResult();
        String str = phone.substring(0,3);
        if(str.equals("170")||str.equals("171")){
            json.setSuccess(false);
            json.setMessage("170-171号段禁止注册");
        }else {
            json = customerService.saveVerificationCode(phone);
        }
        return json;
    }
    /**localhost:6080/customer/getOpenId?code=001NvAUp0pWyfs1dZpUp0I5UUp0NvAUl
     * 获取微信openID
     * @return
     */
    @GetMapping("getOpenId")
    public JsonResult getOpenId(String code,String state) throws Exception {
        JsonResult json =  customerService.getOpenId(code,state);
        return json;
    }
    /**
     * 获取工作每秒的价格区间
     * @return
     */
    @GetMapping("getSecondEarn")
    public JsonResult getSecondEarn(){
        JsonResult json = customerService.getSecondEarn();
        return json;
    }
    /**
     * 获取当前等级可提现金额总数和已提现金额
     * @param phone
     * @return
     */
    @PostMapping("getAmountLimit")
    public JsonResult getAmountLimit(String phone){
        JsonResult json = customerService.getAmountLimit(phone);
        return json;
    }
    /**
     * 用户提取押金
     * @param phone
     * @return
     */
    @GetMapping("applyRefund")
    public JsonResult applyRefund(String phone){
        JsonResult json = customerService.applyRefund(phone);
        return json;
    }
    /**
     * 判断是否认证会员成功
     * @param phone
     * @return
     */
    @GetMapping("judgeMember")
    public JsonResult judgeMember(String phone){
        JsonResult json = customerService.judgeMember(phone);
        return json;
    }
    /**
     * 轮循通知
     * @return
     */
    @GetMapping("circularNotification")
    public JsonResult circularNotification(){
        JsonResult json = customerService.circularNotification();
        return json;
    }
    /**
     *  结束所有小时工作
     * @param workTable
     * @return
     */
    @PostMapping("endAllWork")
    public JsonResult endAllWork(WorkTable workTable) throws Throwable {
        JsonResult json = null;
        Integer state = customerService.judgeState(workTable.getPhone());
        if(state==1){
            //开通会员开始工作
            json = customerService.endAllWork(workTable);
        }else if(state==0){
            //没开通会员开始工作
            json = customerService.endAllWorkNoMember(workTable);
        }
        return json;
    }

//*******************************************工作时间金额统计***********************************************************
    /**
     * 如果断网等错误 再次登录获取
     * @param error
     * @return
     */
    @PostMapping("getError")
    public synchronized JsonResult getError(Integer error,String phone){
        JsonResult json = new JsonResult();
        Integer frozen = customerMapper.getFrozen(phone);
        if(frozen!=null&&frozen==1){
            json.setMessage("您由于违规操作，账户已被冻结");
            json.setSuccess(false);
            return json;
        }
        Integer state = customerService.judgeState(phone);
        if(state==1){
            //开通会员开始工作
            json = runTableService.getError(error,phone);
        }else if(state==0){
            //检测时间与金额是否相符，不相符冻结账户
            WorkTable workTable = customerMapper.getWorkTableNoMembers(phone);
            if(workTable!=null&&200<workTable.getEarnMoney()){
                customerMapper.setFrozen(phone);
                json.setSuccess(false);
                json.setMessage("");
                return json;
            }
            //没开通会员开始工作
            Integer time = customerMapper.getTime(phone);
            if(time==null){
                json.setSuccess(true);
            }else {
                if(time<1200){
                    json = customerService.getErrorNoMember(error,phone);
                } else {
                    json.setMessage("非认证用户可试用20分钟,认证后可永久使用");
                    json.setSuccess(true);
                }
            }
        }else {
            json.setMessage("用户不存在");
            json.setSuccess(false);
        }
        return json;
    }
    /**
     *
     * 进入页面前进行判断，是否还有工作未完成
     * @param phone
     * @return
     */
    @PostMapping("loginJudge")
    public JsonResult loginJudge(String phone){
        JsonResult json = new JsonResult();
        Integer frozen = customerMapper.getFrozen(phone);
        if(frozen!=null&&frozen==1){
            json.setMessage("您由于违规操作，账户已被冻结");
            json.setSuccess(false);
            return json;
        }
        Integer state = customerService.judgeState(phone);
        if(state==1){
            //开通会员开始工作
//            json = customerService.loginMemberJudge(phone);
            json = runTableService.loginMemberJudge(phone);
        }else if(state==0){
            //检测时间与金额是否相符，不相符冻结账户
            WorkTable workTable = customerMapper.getWorkTableNoMembers(phone);
            if(workTable!=null&&200<workTable.getEarnMoney()){
                customerMapper.setFrozen(phone);
                json.setSuccess(false);
                json.setMessage("由于违规操作，您的账户已被冻结");
                return json;
            }
            //没开通会员开始工作
            json = customerService.loginNoMemberJudge(phone);
        }
        return json;
    }

    @Autowired
    RunTableMapper runTableMapper;
    /**localhost:6080/customer/startWork?phone=15603371683
     * 开始工作
     * @param workTable
     * @return
     */
    @PostMapping("startWork")
    public JsonResult startWork(WorkTable workTable){
        JsonResult json = new JsonResult();
//        if(!workTable.getPhone().equals("18712882023")){
//            json.setSuccess(false);
//            return json;
//        }
        Integer frozen = customerMapper.getFrozen(workTable.getPhone());
        if(frozen!=null&&frozen==1){
            json.setMessage("您由于违规操作，账户已被冻结");
            json.setSuccess(false);
            return json;
        }
        Integer state = customerService.judgeState(workTable.getPhone());
        // todo
        if(state==1){
            Integer useTime = customerMapper.getUseTime2(workTable.getPhone());
            if(useTime!=null){
                if(useTime<=12*3600){
                    //查询判断最近的一条工作数据
                    WorkTable workTable1 = runTableService.getWorkTable(workTable.getPhone());
                    if(workTable1!=null&&workTable1.getAllTime()<12*3600){
                        runTableService.startRunTableAgain(Integer.valueOf(workTable1.getId()));
                        json.setSuccess(true);
                    }else if (workTable1!=null&&workTable1.getAllTime()>=12*3600){
                        //查询当前时间
                        long now = (new Date()).getTime();
                        //查询结束时间
                        Date l = runTableMapper.getEndDate(workTable.getPhone());
                        long end = (l).getTime();
                        // 判断结束时间是否超过10小时
                        long time = (now-end)/1000;
                        if(time>10*3600){
                            json = runTableService.startRunTable(workTable);
                        }
//                        json.setSuccess(false);
                    }else {
                        json = runTableService.startRunTable(workTable);
                    }
                }else {
                    json.setMessage("距上次执行结束时间没有超过10小时");
                    json.setSuccess(false);
                }
            }else {
                json = runTableService.startRunTable(workTable);
            }

        }else if(state==0){
            //检测时间与金额是否相符，不相符冻结账户
            WorkTable workTables = customerMapper.getWorkTableNoMembers(workTable.getPhone());
            if(workTables!=null&&200<workTables.getEarnMoney()){
                customerMapper.setFrozen(workTable.getPhone());
                json.setSuccess(false);
                json.setMessage("");
                return json;
            }
            //没开通会员开始工作
            Integer useTime = customerMapper.getUseTimejudge(workTable.getPhone());
            if(useTime!=null&&useTime>=1200){
                json.setMessage("非认证用户可试用20分钟,认证后可永久使用");
                json.setSuccess(false);
            }else {
                json = customerService.startNoMemberWork(workTable);
            }
        }
        return json;
    }
    /**localhost:6080/customer/updateWork?phone=18712882023&earnMoney=12
     * 上传已经走得时间，和赚的金钱
     * @param workTable
     * @return
     */
    @PostMapping("updateWork")
    @ResponseBody
    @Transactional
    public synchronized JsonResult updateWork(WorkTable workTable){
        JsonResult json = new JsonResult();
        WorkLogs workLogs = new WorkLogs();
        Integer frozen = customerMapper.getFrozen(workTable.getPhone());
        if(frozen!=null&&frozen==1){
            json.setMessage("您由于违规操作，账户已被冻结");
            json.setSuccess(false);
            return json;
        }
        BaseInfo baseInfo = customerService.getBaseInfo();
        String phone = workTable.getPhone();
        Integer state = customerService.judgeState(phone);
        if(state==1){
            // todo 调用接口
            workLogs.setPhone(workTable.getPhone());
            workLogs.setCallMethod("customer/updateWork");
            workLogs.setCallName("会员更新数据");
            Integer useTime = customerMapper.getUseTime2(phone);
            Integer allMoney = customerMapper.AllMoney(phone);
            // todo 变化前总时间
            workLogs.setUpdateBeforeDate(useTime);
            // todo 变化前总金额
            workLogs.setBeforeUpAmount(allMoney);
            if(useTime!=null&&useTime<=12*3600){
                Date now = new Date(System.currentTimeMillis());
                Date start = runTableService.getStartTime(workTable.getPhone());
                // todo 结束时间
                workLogs.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));
                // todo 开始时间
                workLogs.setStartDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(start));
                if(start==null){
                    json.setSuccess(false);
                    return json;
                }
                long startTime = start.getTime();
                long nowTime = now.getTime();
                long workTime = (nowTime-startTime)/1000;
                if(workTime>(12*3600-useTime)){
                    workTime=12*3600-useTime;
                }
                // todo 工作时间
                workLogs.setWorkDate(workTime);
                // todo 上传金额
                workLogs.setUpAmount(workTable.getEarnMoney());
                // todo 变化后总时间
                workLogs.setUpdateAfterDate(workTime+useTime);
                if(start!=null){
                    workTable.setAllTime(Integer.valueOf(String.valueOf(workTime)));
                    double moneyHigh = workTime*baseInfo.getEarnPerSecondMaxMember();
                    double moneyLow = workTime*baseInfo.getEarnPerSecondMinMember();
                    //开通会员
                    Integer result ;
                    if(moneyHigh<workTable.getEarnMoney()||moneyLow>workTable.getEarnMoney()){
                        double max = workTime *baseInfo.getEarnPerSecondMaxMember();
                        double min = workTime *baseInfo.getEarnPerSecondMinMember();
                        result = (int)(min + (int)(Math.random() * ((max - min) + 1)));

                    }else {
                        result = workTable.getEarnMoney();
                    }
                    // todo 实际金额
                    workLogs.setActualAmount(result);
                    // todo 变化后总金额
                    workLogs.setAfterUpAmount(result+allMoney);
                }else {
                    workTable.setAllTime(0);
                }
//                System.out.println(workLogs);
                json = runTableService.updateMemberWork(workLogs);
            }else {
                json.setSuccess(false);
            }
        }else if(state==0){
//检测时间与金额是否相符，不相符冻结账户
            WorkTable workTables = customerMapper.getWorkTableNoMembers(workTable.getPhone());
            if(workTable!=null&&200<workTables.getEarnMoney()){
                customerMapper.setFrozen(workTable.getPhone());
                json.setSuccess(false);
                json.setMessage("");
                return json;
            }

            // todo 调用接口
            workLogs.setPhone(workTable.getPhone());
            workLogs.setCallMethod("customer/updateWork");
            workLogs.setCallName("非会员更新数据");
            Integer useTime = customerMapper.getUseTime(workTable.getPhone());
            Integer earnMoney = customerMapper.getEarnMoney(workTable.getPhone());
            // todo 变化前总金额
            workLogs.setBeforeUpAmount(earnMoney);
            // todo 变化前总时间
            workLogs.setUpdateBeforeDate(useTime);
            //  判断最大时间，最大金额（如果超出以最大值计算）
            if(useTime!=null&&useTime<1200){
                Date now = new Date(System.currentTimeMillis());
                // todo 结束时间
                workLogs.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));
                Date start = customerMapper.getUpdateTimek(workTable.getPhone());
                // todo 开始时间
                workLogs.setStartDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(start));
                if(start==null){
                    json.setSuccess(false);
                    return json;
                }
                long startTime = start.getTime();
                long nowTime = now.getTime();
                long workTime = (nowTime-startTime)/1000;
                // todo 工作时间
                workLogs.setWorkDate(workTime);
                if(workTime>(1200-useTime)){
                    workTime=1200-useTime;
                }
                // todo 变化后总时间
                workLogs.setUpdateAfterDate(workTime+useTime);
                double moneyHigh = workTime*baseInfo.getEarnPerSecondMax();
                double moneyLow = workTime*baseInfo.getEarnPerSecondMinMember();

                // todo 上传金额
                workLogs.setUpAmount(workTable.getEarnMoney());
                //没开通会员
                Integer result;
                if(moneyHigh<workTable.getEarnMoney()||moneyLow>workTable.getEarnMoney()){
                    double max = workTime *baseInfo.getEarnPerSecondMax();
                    double min = workTime *baseInfo.getEarnPerSecondMinMember();
                    result = (int)(min + (int)(Math.random() * ((max - min) + 1)));
                }else {
                    result = workTable.getEarnMoney();
                }
                // todo 实际金额
                workLogs.setActualAmount(result);
                // todo 变化后总金额
                workLogs.setAfterUpAmount(result+earnMoney);
                json = customerService.updateNoMemberWork(workLogs);
            }else {
                json.setSuccess(false);
            }
        }
        return json;
    }
    /**localhost:6080/customer/endWork&earnMoney=5000&phone=12
     * 结束工作
     * @param workTable
     * @return
     */
    @PostMapping("endWork")
    public synchronized JsonResult endWork(WorkTable workTable){
        JsonResult json = new JsonResult();
        BaseInfo baseInfo = customerService.getBaseInfo();
        //判断工作是否结束
        Integer state = customerService.judgeState(workTable.getPhone());
        if(state==1){
            Integer endIsNo = customerMapper.endIsNo(workTable.getPhone());
            if(endIsNo!=0){
                Date now = new Date(System.currentTimeMillis());
                Date start = runTableService.getStartTime(workTable.getPhone());
                long startTime = start.getTime();
                long nowTime = now.getTime();
                long workTime = (nowTime-startTime)/1000;
                workTable.setAllTime(Integer.valueOf(String.valueOf(workTime)));
                double moneyHigh = workTime*baseInfo.getEarnPerSecondMaxMember();
                workTable.setEarnMoney((int) moneyHigh);
                json = runTableService.endMemberWork(workTable);
            }else {
                json.setSuccess(true);
            }
        }else if(state==0){
            //检测时间与金额是否相符，不相符冻结账户
            WorkTable workTables = customerMapper.getWorkTableNoMembers(workTable.getPhone());
            if(workTable!=null&&200<workTables.getEarnMoney()){
                customerMapper.setFrozen(workTable.getPhone());
                json.setSuccess(false);
                json.setMessage("由于违规操作，您的账户已被冻结");
                return json;
            }
            Integer endIs = customerMapper.endIs(workTable.getPhone());
            if(endIs!=0){
                Integer useTime = customerMapper.getUseTime(workTable.getPhone());
                if(useTime!=null&&useTime<1200){
                    Date now = new Date(System.currentTimeMillis());
                    Date start = customerMapper.getUpdateTimeend(workTable.getPhone());
                    long startTime = start.getTime();
                    long nowTime = now.getTime();
                    long workTime = (nowTime-startTime)/1000;
                    //没开通会员//todo
                    if(workTime>1200-useTime/1000){
                        workTime = 1200 - useTime/1000;
                    }
                    Integer alltime = Integer.valueOf(String.valueOf(workTime))+useTime;
                    workTable.setAllTime(alltime);
                    double moneyHigh = workTime*baseInfo.getEarnPerSecondMax();
                    workTable.setEarnMoney((int) moneyHigh);
                    json = customerService.endNoMemberWork(workTable);
                }else {
                    customerMapper.endNoMemberWork2(workTable);
                    json.setSuccess(true);
                }
            }else {
                json.setSuccess(true);
            }
        }
        return json;
    }
    //****************************认证************************************************************************

    @Autowired
    CustomerMapper customerMapper;
    /**
     * 获取认证会员的二维码
     * @return
     * @throws Exception
     */
    @GetMapping("getPayHuiHeCode")
    public JsonResult Topay(String phone) throws Exception {
        JsonResult json = new JsonResult();
        if(1==1){
            json.setSuccess(false);
            json.setMessage("正在维护,暂时不支持认证");
            return json;
        }
        Logs logs = new Logs();
        Date date = new Date();
        Map<String,String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<String, String>();
        String str = "VIP";
        String urlString = URLEncoder.encode(str, "UTF-8");
        sParaTemp.put("AppId", "201709100001184369"); //应用ID，等同于商户编号
        sParaTemp.put("Body", str);
        sParaTemp.put("Charset", "UTF-8");
        sParaTemp.put("Format", "JSON");
        sParaTemp.put("Method", "trade.page.pay");
//        sParaTemp.put("NotifyUrl", "http://1833g1872k.imwork.net/transfaner/nofity");
        sParaTemp.put("NotifyUrl", "http://www.p619.cn/earn/transfaner/nofity");

        sParaTemp.put("OutTradeNo", "PH"+phone+sd.format(date));
        sParaTemp.put("PayType", "2");
        sParaTemp.put("Subject", urlString);
        sParaTemp.put("Timestamp", sdf.format(date)); // 请求时间 格式 yyyy-MM-dd HH:mm:ss
        sParaTemp.put("TotalAmount", String.valueOf(298));
        sParaTemp.put("Version", "1.0");
//		sParaTemp.put("Version", "1.0");
        //建立请求
        HuihepaySubmit huihepaySubmit = new HuihepaySubmit();
        String sHtmlText = huihepaySubmit.buildRequest(sParaTemp);
        String[] s = sHtmlText.split("\"");
        logs.setLogsCode(sParaTemp.get("OutTradeNo"));
        logs.setLogsTime(sd.format(date));
        logs.setPhone(phone);
        logs.setLogsContent(str);
        Double d = Double.parseDouble(String.valueOf(298*100));
        Integer m = d.intValue();
        logs.setAmount(m);
        logs.setLogsType("2");
        customerMapper.saveLogs(logs);
        map.put("code",s[3]);
        json.setData(map);
//		json.setData(s[3]);
        json.setSuccess(true);
        return json;
    }

    //    @GetMapping("getPayCode")
    public JsonResult payback(HttpServletResponse response,String phone,HttpServletRequest request) throws IOException {
        JsonResult jsonResult = new JsonResult();

        TimeUtil timeUtil = new TimeUtil();

//        boolean k = timeUtil.utilTime();

//        while (k){
//            jsonResult.setSuccess(false);
//            jsonResult.setMessage("正在维护,暂时不支持认证");
//            return jsonResult;
//        }
        Map<String,String> map = new HashMap<>();
        RendSMS rendSMS = new RendSMS();
        String Code = rendSMS.getRandNum(6);
        Map<String,Object> map1= new HashMap<>();
        map.put("token","HYJNXenkRXR3SX6BN8jKRIQTImFMnnU3"); //表单提交的价格
        map.put("codepay_id","15004"); //支付类型  1：支付宝 2：QQ钱包 3：微信
//        map.put("codepay_id","15004"); //token
        map.put("price","298"); //表单提交的价格
        map.put("type","3"); //支付类型  1：支付宝 2：QQ钱包 3：微信
        map.put("pay_id",phone); //支付人的唯一标识
        map.put("page","4");
        map.put("param",phone+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+Code); //自定义一些参数 支付后返回
//        map.put("notify_url","http://zhulipingtai.com/earn/customer/getAccept");
        map.put("notify_url","http://www.p619.cn/earn/customer/getAccept");
//        map.put("return_url","http://dutufeng.vicp.io//customer/recivePayCode");
        map.put("return_url","http://www.p619.cn/earn/customer/getAccept");
//       /getPayCode
//        if(map.get("price")==null){
//            map.put("price","298");
//        }
        //参数有中文则需要URL编码

        String str = "id="+map.get("codepay_id")+/*"&token="+map.get("token")+*/"&pay_id="+map.get("pay_id")+"&page="+4
                +"&price="+map.get("price")+"&type="+map.get("type")+"&token="+map.get("token")+"&param="
                +map.get("param")+"&notify_url="+map.get("notify_url")+"&return_url="+map.get("return_url");
        String sign = MD5Utils.getMD5(str);
        String url="http://codepay.fateqq.com:52888/creat_order?"+str+"&sign="+sign;
//        response.sendRedirect(url);
        JSONObject json = readJsonFromUrl(url);
        map1.put("code",JSONObject.fromObject(json.get("a")).get("qrcode"));
        Logs logs = new Logs();

        logs.setLogsCode(map.get("param"));
        logs.setLogsTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        logs.setPhone(phone);
        logs.setLogsContent("VIP");
        Double d = Double.parseDouble(String.valueOf(298*100));
        Integer m = d.intValue();
        logs.setAmount(m);
        logs.setLogsType("2");
        customerMapper.saveLogs(logs);


        jsonResult.setSuccess(true);
        jsonResult.setData(map1);
        jsonResult.setMessage(String.valueOf(JSONObject.fromObject(json.get("a")).get("msg")));
        return jsonResult;
    }

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject();
            json.put("a",jsonText);
            return json;
        } finally {
            is.close();
        }
    }

    @PostMapping("getAccept")
    public String getAccept(HttpServletRequest request){

        String phone = request.getParameter("pay_id");
        String param = request.getParameter("param");

        Logs logs = new Logs();
        logs.setIsSure(1);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logs.setTimeSure(sd.format(new Date()));
        logs.setLogsCode(param);
        logs.setFalseBack("支付成功！！！！");
        customerMapper.updateLogs(logs);

        RendSMS rendSMS = new RendSMS();
        rendSMS.sms_api2(phone,"认证成功，请重新进入APP");

        //todo 如果付款成功 则改变会员
        customerMapper.updateMemberState(phone);
        //但会员认证成功以后，会给一级，二级，三级好友钱包中分别放入60,30,10元
        //首先查询一二三级好友
        String friends1 = customerMapper.getFriends1(phone);
        String friends2 = customerMapper.getFriends2(phone);
        String friends3 = customerMapper.getFriends3(phone);
        //将奖励的好友的钱放入钱包
        if(friends1!=null){
            customerMapper.saveWalletMoney(6000,friends1);
            String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            customerMapper.saveInvitationLogs(startTime,6000,friends1);
            if(friends2!=null){
                customerMapper.saveWalletMoney(3000,friends2);
                customerMapper.saveInvitationLogs(startTime,3000,friends2);
                if(friends3!=null){
                    customerMapper.saveWalletMoney(1000,friends3);
                    customerMapper.saveInvitationLogs(startTime,1000,friends3);
                }
            }
        }
        return "OK";
    }

    @GetMapping("getPayCode")
    public JsonResult payAccept(HttpServletResponse response,String phone,HttpServletRequest request) throws IOException {
        JsonResult jsonResult = new JsonResult();

        BaseInfo baseInfo = customerMapper.getBaseInfo();
        Map<String,String> map = new HashMap<>();
        map.put("bankCode",baseInfo.getBankCode());
        map.put("bankName",baseInfo.getBankName());

        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        TimeUtil timeUtil = new TimeUtil();

        boolean k = timeUtil.utilTime(date);

        while (!k) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("请在6:00-23:00期间认证");
            return jsonResult;
        }

        //根据手机号码查询是否在一小时内生成过数据
        Double num = customerMapper.getAmountNum(phone);

        if(num==null){
            boolean flag = true;
            double t = 0;
            DecimalFormat df = new DecimalFormat("######0.00");

            //查询数据库内规定时间内的金额
            List<Double> list = customerMapper.getAmount();
            int index = list.size();

            Random r = new Random();
            t = 299-Double.parseDouble(df.format(r.nextFloat()))-r.nextInt(5);

            for(int ik = 0;ik < index; ik++){
                if(t==list.get(ik)){
                    flag = false;
                    break;
                }
            }
            if(flag){
                //将获取的金额存入数据库
                customerMapper.saveAmount(phone,t,date);
            }
            map.put("amount", String.valueOf(t));
            jsonResult.setSuccess(true);
            jsonResult.setMessage("获取成功");
            jsonResult.setData(map);
        }else {
            map.put("amount", String.valueOf(num));
            jsonResult.setMessage("获取成功");
            jsonResult.setSuccess(true);
            jsonResult.setData(map);
        }

        return jsonResult;
    }

    @GetMapping("getNotice")
    public JsonResult getNotice(String phone){

        JsonResult json = new JsonResult();
        //根据账号查询是否获取订单超过两次
        Integer no = customerMapper.getEveryDay(phone);
        if(no<3){
            customerMapper.updateNotice(phone);
            json.setSuccess(true);
            json.setMessage("已提交客服审核认证！每天限提交3次");
        }else {
            json.setSuccess(false);
            json.setMessage("今天已提交认证3次，请明天再提交");
            json.setData("");
        }
        return json;
    }
}
